import React, { useEffect, useState, useRef } from "react";
import ReactDOM from "react-dom/client";
import "./style.css";

type WordData = {
  word: string;
  phonetic: string;
  definition: string;
  sentence: string;
};

const API_BASE = "http://localhost:8000/api";

function App() {
  const [wordData, setWordData] = useState<WordData | null>(null);
  const [readSentence, setReadSentence] = useState(false);
  const [loop, setLoop] = useState(false);
  const [speed, setSpeed] = useState(1.0);
  const audioRef = useRef<HTMLAudioElement | null>(null);

  useEffect(() => {
    fetch(`${API_BASE}/word`)
      .then(res => res.json())
      .then(setWordData);
  }, []);

  const playAudio = async () => {
    if (!wordData) return;
    const text = readSentence ? wordData.sentence : wordData.word;
    const url = `${API_BASE}/pronounce?text=${encodeURIComponent(text)}`;
    if (audioRef.current) {
      audioRef.current.pause();
      audioRef.current.currentTime = 0;
    }
    const audio = new Audio(url);
    audio.playbackRate = speed;
    audio.loop = loop;
    audioRef.current = audio;
    audio.play();
  };

  if (!wordData) return <div>加载中...</div>;

  return (
    <div className="word-card">
      <div className="controls">
        <label className="switch-label">
          <input type="checkbox" checked={readSentence} onChange={e => setReadSentence(e.target.checked)} />
          朗读句子
        </label>
        <label className="switch-label">
          <input type="checkbox" checked={loop} onChange={e => setLoop(e.target.checked)} />
          循环播放
        </label>
        <select value={speed} onChange={e => setSpeed(Number(e.target.value))}>
          <option value={1.0}>1.0x 倍速</option>
          <option value={0.75}>0.75x</option>
          <option value={1.25}>1.25x</option>
        </select>
      </div>
      <div className="word">{wordData.word}</div>
      <div className="phonetic">{wordData.phonetic}</div>
      <div className="definition">{wordData.definition}</div>
      <button className="play-btn" onClick={playAudio}>播放</button>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")!).render(<App />); 